import { Settings as LayoutSettings } from '@ant-design/pro-components';
import { RunTimeLayoutConfig } from '@umijs/max';
import defaultSettings from '../config/defaultSettings';
import { requestConfig } from './requestConfig';
import React from 'react';
import IconFont from './components/IconFont';
import { APP_VERSION, AUTHOR_EMAIL, COPYRIGHT, LOGIN_PATH } from './constants';
import { getMenu, getPermissionInfo } from './services/auth';
import { handleLogout } from './utils/authUtils';
import { checkRespSuccessful } from './utils/serviceUtils';
import { getMenuCollapsedStatus, setMenuCollapsedStatus } from './utils/systemConfigManegerUtils';
import { dictListToGroup } from './utils/dictUtils';
import { getDictSelectList } from './services/system/dict';
import { menuFormat } from './utils/menuUtils';
import { isFullscreen } from './utils/fullscreenUtils';
import RootEventListenner from './components/RootEventListenner';
import Mousetrap from 'mousetrap';
import Setting from './components/Setting';
import UserManage from './components/UserManage';

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<System.InitialStatusType> {
  const collapsed = getMenuCollapsedStatus();
  // eslint-disable-next-line @typescript-eslint/no-use-before-define
  const fullscreen = isFullscreen();
  // 如果不是登录页面，执行
  // const { location } = history;
  if (location.pathname !== LOGIN_PATH) {
    const getUserInfoRes = await getPermissionInfo();
    const getDictSelectListRes = await getDictSelectList();
    let menuTree: System.MenuTreeNode[] = [];
    const getMenuRes = await getMenu();
    if (checkRespSuccessful(getMenuRes) && getMenuRes.data) {
      menuTree = menuFormat(getMenuRes.data);
    }
    if (checkRespSuccessful(getUserInfoRes) && checkRespSuccessful(getDictSelectListRes)) {
      const dictGroup = dictListToGroup(getDictSelectListRes.data || []);
      return {
        settings: defaultSettings as Partial<LayoutSettings>,
        collapsed,
        fullscreen,
        currentUser: getUserInfoRes.data,
        menuTree,
        ...dictGroup,
      };
    }
  }
  return {
    settings: defaultSettings as Partial<LayoutSettings>,
    collapsed,
    fullscreen,
  };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {
  const changeFlag = window.innerWidth >= 768 && initialState?.collapsed;

  const SettingEle = (
    <div
      key="setting"
      style={{
        height: 26,
        width: 26,
        padding: 4,
        fontSize: 18,
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
      }}
    >
      <Setting />
    </div>
  );

  const UserMenuEle = (
    <span
      style={{
        height: changeFlag ? 18 : 38,
        width: changeFlag ? 18 : undefined,
        boxSizing: changeFlag ? 'content-box' : 'border-box',
        padding: changeFlag ? 4 : window.innerWidth >= 768 ? 16 : undefined,
        margin: changeFlag ? undefined : '0 4px',
        cursor: 'pointer',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      }}
    >
      <UserManage />
    </span>
  );

  Mousetrap.bind('esc', () => {
    if (initialState?.immersionMode) {
      setInitialState({
        ...initialState,
        immersionMode: false,
      });
    }
  });

  return {
    logo: '/assets/logo.png',
    menu: {
      locale: false,
      params: {
        menuTree: initialState?.menuTree,
      },
      request: async (params) => {
        return params.menuTree;
      },
    },
    // 处理全屏展示
    menuRender: (props, defaultDom) => {
      return initialState?.immersionMode ? null : defaultDom;
    },
    // 处理隐藏 tab bar
    className: initialState?.immersionMode ? 'hide-tab-bar' : undefined,
    // 菜单折叠状态
    collapsed: initialState?.collapsed,
    // 菜单折叠状态切换
    onCollapse: (status: boolean) => {
      setMenuCollapsedStatus(status);
      setInitialState({ ...initialState, collapsed: status });
    },
    // 禁用默认的折叠菜单按钮
    collapsedButtonRender: false,
    actionsRender: () => [changeFlag ? UserMenuEle : SettingEle],
    avatarProps: {
      render: () => {
        if (changeFlag) {
          return SettingEle;
        } else {
          return UserMenuEle;
        }
      },
    },
    // 启用水印
    waterMarkProps: {
      content: initialState?.currentUser?.name,
    },
    onPageChange: () => {
      if (window.innerWidth < 768) {
        setMenuCollapsedStatus(true);
        setInitialState({ ...initialState, collapsed: true });
      }
      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser) {
        handleLogout();
      }
      // 临时处理布局偶现不生效 BUG
      setTimeout(() => {
        const pageContainer = document.querySelector('.ant-pro-page-container-children-content');
        if (!pageContainer) {
          return;
        }
        const { padding } = window.getComputedStyle(pageContainer);
        if (padding === '' || padding === '0px' || padding === '0') {
          location.reload();
        }
      });
    },
    links: [
      <span key="copyright">
        <IconFont type="icon-banquan" />
        <span>{COPYRIGHT}</span>
      </span>,
      <a key="email" href={`mailto:${AUTHOR_EMAIL}`}>
        <IconFont type="icon-zujian-youxiang" />
        <span>{AUTHOR_EMAIL}</span>
      </a>,
      <span key="version">
        <IconFont type="icon-versionSix" />
        <span>{APP_VERSION}</span>
      </span>,
    ],
    menuHeaderRender: undefined,
    childrenRender: (dom) => {
      return (
        <>
          <RootEventListenner
            onFullscreenChange={() => {
              setInitialState({
                ...initialState,
                fullscreen: isFullscreen(),
              });
            }}
          />
          {dom}
        </>
      );
    },
    ...initialState?.settings,
  };
};

/**
 * @name request 配置，可以配置错误处理
 * 它基于 axios 和 ahooks 的 useRequest 提供了一套统一的网络请求和错误处理方案。
 * @doc https://umijs.org/docs/max/request#配置
 */
export const request = {
  ...requestConfig,
};
